package 环形数组实现队列;

import java.util.Iterator;

public class ArrayQueue1<E> implements Iterable<E>{
    private int head = 0;
    private int tail = 0;
    private E[] array;
    private int capacity;

    @SuppressWarnings("all") // 让idea不警告
    public ArrayQueue1(int capacity) {
        this.capacity = capacity + 1;
        array = (E[]) new Object[capacity];
    }

    public ArrayQueue1() {
    }

    /**
     * 向队列尾插入值
     * @param value 待插入值
     * @return 插入成功返回true,插入失败返回false
     */
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        array[tail] = value;
        tail = (tail + 1) % capacity;
        return true;
    }

    /**
     * 从队列头获取值, 并移除
     * @return 如果队列非空返回对头值, 否则返回null
     */
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E value = array[head];
        head = (head + 1) % capacity;
        return value;
    }

    /**
     * 从队列头获取值, 不移除
     * @return 如果队列非空返回对头值, 否则返回null
     */
    public E peak() {
        if (isEmpty()) {
            return null;
        }
        return array[head];
    }

    /**
     * 检查队列是否为空
     * @return 空返回true, 否则返回false
     */
    public boolean isEmpty() {
        return tail == head;
    }

    /**
     * 检查队列是否为满
     * @return 满返回true, 否则返回false
     */
    public boolean isFull(){
        return (tail + 1) % capacity == head;
    }
    @Override
    public Iterator<E> iterator() {
        return new Iterator<>() {
            int p = head;

            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E value = array[p];
                p = (p + 1) % capacity;
                return value;
            }
        };
    }
}
